
/* -----------------
* brief 
* 1. this is code gen by tools 
* 2. mvc code are driver by the model defined with the same filename,
	 for example:
	 there is a Xmodel struct define in xmodel.go file, after the script run (lego model-mvc module_name xmodel)
     it will auto create the code under the module's path
	 m --> xmodel.go
	 v --> view
	 c --> xmodel_ctrl 
* 3. you should modify this code if it doesn't satisfy your purpose   
*/

package controller

import (
	"encoding/json"
	"fmt"
	mchcorev2 "github.com/chanxuehong/wechat/mch/core"
	"github.com/chanxuehong/wechat/mchv3/marketing/busifavor"
	"github.com/mjiulee/lego"
	"github.com/valyala/fasthttp"
	"saas_sys_base/common"

	. "saas_sys_base/modules/coupon/service"
)

type MchCouponApiCtrl struct {
	service  CouponApiService
}


func init () {
	vc:= new(MchCouponApiCtrl)
	_ctrlList = append(_ctrlList,vc)
}

func (vc*MchCouponApiCtrl)CtrlInfo() string {
	return "MchCouponCtrl"
}

func (vc*MchCouponApiCtrl)RoutInit() {
	lego.APIPOST("/api/mod/coupon/create_coupon", vc.CreateCoupon, true)
	lego.APIPOST("/api/mod/coupon/get_coupon_sign", vc.GetCouponSign, true)
	lego.APIPOST("/api/mod/coupon/get_coupon_callback", vc.GetCouponCallback, true)
}


func (vc *MchCouponApiCtrl) CreateCoupon(ctx *fasthttp.RequestCtx) {
	ctxExt := lego.RequestCtxExtent{ctx}
	response := make(map[string]interface{})
	code := 0
	msg := "success"

	type Request struct {
		busifavor.MchCoupon `json:"mch_coupon"`
		CouponMode common.COUPON_MODE `json:"coupon_mode"`
	}

	type Resp struct {
        CouponId int64 `json:",string"`
		WxCouponStockId string `json:",omitempty"`
	}

	var request Request
	var resp Resp

	for {
		sessionData := common.GetSessionData(&ctxExt)
		who := sessionData.AppTokenWho

		requestByte := ctxExt.PostBody()
		err := json.Unmarshal(requestByte, &request)
		if err != nil {
			code = -1
			msg = err.Error()
			break
		}

		err = busifavor.CheckParaForCreateStock(&request.MchCoupon) //参数校验
		if err != nil {
			code = -1
			msg = fmt.Sprintf("para err: %s", err.Error())
			break
		}
		// TODO 需要修改接口参数
		coupon, wxCouponResp, err := vc.service.CreateCouponByWho(who, &request.MchCoupon, request.CouponMode)
		if err != nil {
			code = -1
			msg = err.Error()
			break
		}

		resp.CouponId = coupon.Id
		if wxCouponResp != nil { //兼容微信券模式会进入这个分支，代表微信返回的批次号（StockId）
			resp.WxCouponStockId = wxCouponResp.StockId
		}

		response["data"] = resp
		break
	}

	response["code"] = code
	response["msg"] = msg

	ctxExt.JSON(200, response)

}


func (vc *MchCouponApiCtrl) GetCouponSign(ctx *fasthttp.RequestCtx) {
	ctxExt := lego.RequestCtxExtent{ctx}
	response := make(map[string]interface{})
	code := 0
	msg := "success"

	type Request struct {
		StockId string `json:"stock_id"  vd:"len($)>1"`
		OutRequestNo string `json:"out_request_no" vd:"len($)>1"`
	}

	type Resp struct {
		SendCouponParams mchcorev2.SendCouponParams `json:"send_coupon_params"`
		SendCouponMerchant string `json:"send_coupon_merchant"`
		Sign string `json:"sign"`

	}

	var request Request
	var resp Resp

	for {
		sessionData := common.GetSessionData(&ctxExt)
		who := sessionData.AppTokenWho

		requestByte := ctxExt.PostBody()
		err := json.Unmarshal(requestByte, &request)
		if err != nil {
			code = -1
			msg = err.Error()
			break
		}

		if err := lego.Validate(request); err != nil {
			code = 100
			msg = err.Error()
			break
		}

		// TODO 需要修改接口参数
		couponDb, sign, sendCouponParams, err := vc.service.GetCouponSign(who, request.StockId, request.OutRequestNo)
		if err != nil {
			code = -1
			msg = err.Error()
			break
		}

		resp.SendCouponParams = *sendCouponParams
		resp.SendCouponMerchant = couponDb.BelongMerchant
		resp.Sign = sign

		response["data"] = resp
		break
	}

	response["code"] = code
	response["msg"] = msg

	ctxExt.JSON(200, response)

}

func (vc *MchCouponApiCtrl) GetCouponCallback(ctx *fasthttp.RequestCtx) {
	ctxExt := lego.RequestCtxExtent{ctx}
	response := make(map[string]interface{})
	code := 0
	msg := "success"

	type Request struct {
	}

	type Resp struct {
		*busifavor.GetCallbackResp
	}

	var request Request
	var resp Resp

	for {
		sessionData := common.GetSessionData(&ctxExt)
		who := sessionData.AppTokenWho

		requestByte := ctxExt.PostBody()
		err := json.Unmarshal(requestByte, &request)
		if err != nil {
			code = -1
			msg = err.Error()
			break
		}

		// TODO 需要修改接口参数
		resp.GetCallbackResp, err = vc.service.GetCouponCallback(who)
		if err != nil {
			code = -1
			msg = err.Error()
			break
		}

		response["data"] = resp
		break
	}

	response["code"] = code
	response["msg"] = msg

	ctxExt.JSON(200, response)

}